package com.honeycomb.common;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.honeycomb.utils.SystemConstants;
import com.honeycomb.utils.SystemTools;

public class HCMainExceptionHandler implements HandlerExceptionResolver {  
  
	protected Logger logger = LogManager.getLogger(this.getClass());
	
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    	
    	
        Map<String, Object> parameters = new HashMap<String, Object>();  
        parameters.put("message", logErrorMessage(ex) );
        
        String hdAccep = request.getHeader("accept");
        String hdXReq = request.getHeader("X-Requested-With");
        
        if ( (hdAccep != null && hdAccep.indexOf("application/json") > -1) || (hdXReq != null && hdXReq.indexOf("XMLHttpRequest") > -1) ) { //如果是异步请求
        	//JSON格式返回 
        	JSONObject obj = new JSONObject();
        	obj.put("result", SystemConstants.AJAX_FAILED_ALERT);
        	obj.putAll(parameters);
        	
        	response.setCharacterEncoding(request.getCharacterEncoding());
        	response.setContentType("application/json");
            try {  
                response.getWriter().println(obj.toJSONString());  
            } catch (IOException e) {  
            	logger.error("Exception happens when write error message to response.", e); 
            }  
            return new ModelAndView();  
        }
        else {// 如果不是异步请求  
            // Apply HTTP status code for error views, if specified.  
            // Only apply it if we're processing a top-level request.  
        	return new ModelAndView(getNextPage(ex), parameters); 
        	
        }
    }
    
    private String logErrorMessage(Exception ex) {
    	if (ex instanceof SessionTimeoutException) {
    		
    		return "登录信息超时，请先登录后再操作！";
    	}
    	else {  // default exception message
        	String exId = SystemTools.getUUIDString();        	
        	logger.error("HCMainExceptionHandler capture an exception with id " + exId, ex);
    		return "消息ID：" + exId + " ， 详细信息：" + ex.getMessage();
    	}
    	
    }
    
    private String getNextPage(Exception ex) {
    	if (ex instanceof SessionTimeoutException) {
    		return "login";
    	}
    	else {  // default exception page
    		return "error";
    	}    	
    }
        
}  